// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var code = (
  "(function(i) {" +
  "if (!('__numbered_tabs_orig_title' in document)) {" +
  "  document.__numbered_tabs_orig_title = document.title;" +
  "};" +
  "var t = document.title.replace(/^[0-9]+: ?/, '');" +
  "if (t != document.__numbered_tabs_orig_title) {" +
  "  t = document.__numbered_tabs_orig_title = document.title;" +
  "};" +
  "document.title = '' + i + ': ' + t;" +
  "})");

function updateTitle(number, tab) {
  if (!tab.url.match("^http[s]?:")) return;
  var script = { code: code + "(" + (number + 1) + ")" };
  chrome.tabs.executeScript(tab.id, script);
}

function refreshAllInWindow(windowId) {
  function allTabs(/* Array[Tab] */ tabs) {
    for (var i = 0; i < tabs.length; i++) {
      updateTitle(i, tabs[i]);
    }
  }
  chrome.tabs.getAllInWindow(windowId, allTabs);
}

function refreshAll(ignored, ignored) {
  refreshAllInWindow(undefined);
}

function onUpdated(/* integer */ tabId, /* object */ changeInfo, /* Tab */ tab) {
  function allTabs(/* Array[Tab] */ tabs) {
    for (var i = 0; i < tabs.length; i++) {
      if (tabs[i].id == tabId) {
        updateTitle(i, tabs[i]);
        return;
      }
    }
  }
  chrome.tabs.getAllInWindow(undefined, allTabs);
}

function onDetached(tabId, detachInfo) {
  refreshAllInWindow(detachInfo.oldWindowId);
}

chrome.tabs.onUpdated.addListener(onUpdated);
chrome.tabs.onDetached.addListener(onDetached);
chrome.tabs.onAttached.addListener(refreshAll);
chrome.tabs.onCreated.addListener(refreshAll);
chrome.tabs.onMoved.addListener(refreshAll);
chrome.tabs.onRemoved.addListener(refreshAll);
